import {
  CallHandler,
  ExecutionContext,
  HttpStatus,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { map, Observable } from 'rxjs';

@Injectable()
export class RestResponseTransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    // console.log('---200----RestResponseTransformInterceptor--');

    // 修改 nestjs post 方法成功响应 http-status 201 为 200
    let code = HttpStatus.OK;
    const request = context.switchToHttp().getRequest<Request>();
    if (request.method === 'POST') {
      code = HttpStatus.CREATED;

      context.switchToHttp().getResponse().status(code);
    }

    return next.handle().pipe(
      map((res) => {
        // console.log('----RestResponseTransformInterceptor res : ', res);

        // const data = res.data;
        // const meta = res.meta;

        // if (data) {
        //   return {
        //     code: 200,
        //     data,
        //     meta,
        //     message: 'success',
        //   };
        // }

        return {
          code,
          data: res,
          message: 'success',
        };
      }),
    );
  }
}
